package com.promise.paging

import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.arch.lifecycle.ViewModelProviders
import android.arch.paging.PagedList
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.support.v7.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : FragmentActivity() {
    private  val KEY_SUBREDDIT = "subreddit"
    private  val DEFAULT_SUBREDDIT = "androiddev"
    private var listAdapter : UserPagedListAdapter? = null
    private lateinit var model: UserViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        model = getViewModel()
        listAdapter = UserPagedListAdapter()
        val linear =LinearLayoutManager(this)
        recycler.adapter = listAdapter
        recycler.layoutManager = linear
        model.posts.observe(this, Observer<PagedList<QuestsData>> {
            listAdapter!!.submitList(it)
        })
        val subreddit = savedInstanceState?.getString(KEY_SUBREDDIT) ?: DEFAULT_SUBREDDIT
        model.showSubreddit(subreddit)
    }

    private fun getViewModel(): UserViewModel {
        return ViewModelProviders.of(this, object : ViewModelProvider.Factory {
            override fun <T : ViewModel?> create(modelClass: Class<T>): T {
                val repo = ServiceLocator.instance()
                        .getRepository()
                @Suppress("UNCHECKED_CAST")
                return UserViewModel(repo) as T
            }
        })[UserViewModel::class.java]
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putString(KEY_SUBREDDIT, model.currentSubreddit())
    }

}
